package com.castile.oa;

import java.io.*;
import java.net.URL;
import java.security.SecureClassLoader;

/**
 * @description: 从Jar包中加载对象
 * @author: Castile
 * @create: 2024-04-11 00:02
 * @Version 1.0
 **/
public class SalaryJarClassLoader extends SecureClassLoader {

    private String jarFile;

    public SalaryJarClassLoader(String jarFile) {
        this.jarFile = jarFile;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String filePath = name.replace(".", "/").concat(".class");
        URL url;

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        InputStream inputStream = null;
        byte[] b = new byte[100];
        int code;
        try {
            url = new URL("jar:file:" + this.jarFile + "!/" + filePath);
            inputStream = url.openStream();

            while ((code = inputStream.read()) != -1) {
                byteArrayOutputStream.write(code);
            }
            b = byteArrayOutputStream.toByteArray();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {

                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        System.out.println("myclass 字节数组大小为： " + b.length);
        return this.defineClass(name, b, 0, b.length);
    }
}
